﻿using System;
using System.Configuration;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Data.SqlClient;
using System.Security.Cryptography;

public partial class Login : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
    if (!String.IsNullOrEmpty(Request.Params["logout"]))
    {
      FormsAuthentication.SignOut();
      Response.Redirect("People.aspx");
    }
    if (User.Identity.IsAuthenticated)
    {
      Response.Redirect("People.aspx");
    }
  }

  protected void bnLogon_Click(object sender, EventArgs e)
  {
    if (ValidateUser(txtUserName.Text, txtUserPass.Text))
      FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, true);
    else
      lblMsg.Text = "Incorrect";
  }

  /// <summary>
  /// Filter out the fat fingers who get their passwords wrong
  /// </summary>
  bool ValidateUser(string user, string pass)
  {
    using (SqlConnection conn = Conn.GetOpened())
    {
      string sql = "select email from users where email = @email and password = @password";
      SqlCommand cmd = new SqlCommand(sql, conn);
      cmd.Parameters.AddWithValue("@email", user);
      cmd.Parameters.AddWithValue("@password", Util.HashAndSalt(pass));
      return cmd.ExecuteScalar() is string;
    }
  }

}
